<template>
  <div class="container" @contextmenu.prevent @selectstart.prevent>
    <div class="user-info-container">
      <!-- 左侧用户信息 -->
      <div class="user-details">
        <el-avatar class="avatar" :src="avatarUrl"></el-avatar>
        <!-- 只在 salaryData 存在时显示 -->
        <h2 v-if="salaryData">{{ salaryData.name }}</h2>
        <p><strong class="info-label">所 在 部 门 ：</strong><span class="info-content">{{ salaryData ? salaryData.department : '' }}</span></p>
        <p><strong class="info-label">职务（职级）：</strong><span class="info-content">{{ salaryData ? salaryData.positionRank : '' }}</span></p>
        <p><strong class="info-label">级 别 - 档 次 ：</strong><span class="info-content">{{ salaryData ? salaryData.gradeLevel : '' }}</span></p>
      </div>

      <div class="vertical-line"></div>

      <!-- 右侧工资明细 -->
      <div class="salary-details">
        <div class="header-section">
          <h2 v-if="salaryData">{{ salaryData.name }} {{ selectedMonth }} 工资表信息</h2>
          <el-date-picker v-model="selectedMonth" type="month" placeholder="选择月份" value-format="yyyy-MM" @change="handleMonthChange" />
        </div>

        <!-- 收入类项目表格 -->
        <div class="section-title">收入项目</div>
        <el-table :data="incomeItems" style="width: 100%">
          <el-table-column label="项目" prop="item"></el-table-column>
          <el-table-column label="金额" align="right">
            <template #default="{ row }">
              <span class="income-item">
                {{ formatCurrency(row.amount, true) }}
              </span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 应发合计 -->
        <div class="summary-section">
          <p class="total-income">应发合计: {{ salaryData ? salaryData.totalIncome : '--' }}</p>
        </div>

        <!-- 扣款类项目表格 -->
        <div class="section-title deduction-title">应扣项目</div>
        <el-table :data="deductionItems" style="width: 100%">
          <el-table-column label="项目" prop="item"></el-table-column>
          <el-table-column label="金额" align="right">
            <template #default="{ row }">
              <span class="deduction-item">
                {{ formatCurrency(row.amount, false) }}
              </span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 应扣合计 -->
        <div class="summary-section">
          <p class="total-deductions">应扣合计: {{ salaryData ? salaryData.totalDeductions : '--' }}</p>
        </div>

        <div class="summary-section">
          <p class="actual-salary">实发工资: {{ salaryData ? salaryData.netSalary : '--' }}</p>
        </div>

        <div class="remark-container">
          <p><strong>备注：</strong> {{ salaryData ? salaryData.remark : '--' }}</p>
        </div>
        
        <!-- 个税专项附加扣除额度 -->
        <div class="tax-deduction-container">
          <p><strong>个税专项附加扣除额度：</strong> {{ salaryData ? salaryData.taxDeduction : '--' }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      avatarUrl: "/img/avatar.jpg",
      selectedMonth: this.getCurrentMonth(), // 默认设置为当前月
      salaryData: null, // 改为null更清晰
    };
  },
  computed: {
    jobNumber() {
      console.log("获取工号: ", this.$store.getters.userSn); // 打印工号
      return this.$store.getters.userSn; // 从 Vuex 获取工号
    },
    incomeItems() {
      if (!this.salaryData) return []; // 添加空值检查
      const incomeMapping = {
        职务职级工资: "positionSalary",
        级别工资: "gradeSalary",
        生活性补贴: "livingAllowance",
        工作性津贴: "workAllowance",
        信访岗位津贴: "petitionAllowance",
        公务交通补贴: "trafficSubsidy",
        通讯补贴: "communicationSubsidy",
        物业补贴: "propertySubsidy",
        基础绩效奖: "basicPerformance",
        其他: "otherIncome",
        补发工资: "backPay",
        年终一次性奖金: "annualBonus",
      };

      return Object.entries(incomeMapping).map(([itemName, field]) => ({
        item: itemName,
        amount: Math.abs(this.salaryData[field] || 0),
      }));
    },

    deductionItems() {
      if (!this.salaryData) return []; // 添加空值检查
      const deductionMapping = {
        养老保险: "pensionInsurance",
        医疗保险: "medicalInsurance",
        住房公积金: "housingFund",
        工会费: "unionFee",
        药费: "medicalFee",
        房租: "rent",
        扣工资: "salaryDeduction",
        所得税: "incomeTax",
        扣款: "totalDeduction",
        补扣养老保险: "backPension",
        补扣公积金: "backHousingFund",
        补扣医保: "backMedical",
      };

      return Object.entries(deductionMapping).map(([itemName, field]) => ({
        item: itemName,
        amount: -Math.abs(this.salaryData[field] || 0),
      }));
    },
  },
  methods: {
    getCurrentMonth() {
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = currentDate.getMonth() + 1; // JavaScript months are zero-indexed
      return `${year}-${month < 10 ? "0" + month : month}`; // 格式化为 "YYYY-MM"
    },

    // 简化版的获取工资数据
    async fetchSalaryDataForMonth() {
      try {
        const response = await this.$API.salary.reqSalaryStatement(
          this.selectedMonth,
          this.jobNumber
        );

        console.log(response.data);

        // 更新工资数据
        this.salaryData = response.data;

        // 更新页面标题
        document.title = `${response.data.name}的${this.selectedMonth}工资单`;
      } catch (error) {
        console.error("数据获取失败:", error);
        this.$message.error("数据加载失败，请稍后重试");
      }
    },
    handleMonthChange() {
      this.fetchSalaryDataForMonth();
    },
    // 数字前面不显示    "+" : "-"符号
    formatCurrency(value, isIncome) {
      if (value === null || value === undefined) return "--";
      return `¥ ${Math.abs(value).toFixed(2)}`; // 去掉符号，直接显示金额
    },
  },

  created() {
    this.fetchSalaryDataForMonth();
  },
};
</script>




<style scoped>

/* 保持原有布局样式 */
.container {
  display: flex;
  justify-content: left;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 10px;
  justify-content: center; /* 修改为居中 */
  user-select: none; /* 禁止文本选择 */
}

.user-info-container {
  display: flex;
  width: 90%;
  max-width: 1200px;
  align-items: flex-start;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

/* 保留原有的样式 */
.section-title {
  font-size: 18px;
  font-weight: bold;
  margin: 20px 0 10px;
  color: #67c23a;
}

.deduction-title {
  color: #f56c6c;
  border-top: 2px solid #eee;
  padding-top: 20px;
}

.summary-section {
  margin-top: 20px;
  text-align: right;
}

.total-income {
  font-size: 18px;
  font-weight: bold;
  color: #67c23a;
}

.total-deductions {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.actual-salary {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
  margin-top: 12px;
}

/* 新增类样式来控制收入和扣款的颜色 */
.income-item {
  color: #67c23a;
}

.deduction-item {
  color: #f56c6c;
}


.user-details {
  flex: 0 0 320px;
  text-align: center;
  margin-right: 15px;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f0f8ff;
  padding: 15px;
}

.user-details .avatar {
  width: 150px;
  height: 150px;
  margin-bottom: 10px;
}

.user-details p {
  display: flex;
  width: 100%;
  margin: 8px 0;
  align-self: flex-start;
}

.info-label {
  flex: 0 0 130px;
  text-align: right;
  padding-right: 12px;
  white-space: nowrap;
}

.info-content {
  flex: 1;
  text-align: left;
  overflow-wrap: break-word;
}

.salary-details {
  flex: 1;
  background-color: #fafafa;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.vertical-line {
  width: 1px;
  background-color: #ccc;
  margin: 0 15px;
  height: 100%;
}

/* 单独为个税专项附加扣除额度设置的样式 */
.tax-deduction-container {
  background-color: #f3f9fb;
  padding: 10px;
  border-radius: 5px;
  margin-top: 20px;
  border-left: 5px solid #2196f3;
  color: #333;
}

.remark-container {
    background-color: #f9f9f9; /* 背景色 */
    border: 1px solid #ccc; /* 边框 */
    padding: 10px; /* 内边距 */
    border-radius: 5px; /* 圆角边框 */
    margin-top: 20px; /* 顶部外边距 */
    font-family: Arial, sans-serif; /* 字体 */
    font-size: 14px; /* 字号 */
    color: #333; /* 字体颜色 */
}

/* 优化移动端布局 */
@media (max-width: 768px) {
  .header-section {
    flex-direction: column;
    align-items: flex-start;
  }
  .user-details {
    flex: 0 0 auto;
    width: 100%;
  }

  .el-date-picker {
    width: 100%;
    margin-top: 10px;
  }
}
</style>
